import { login } from "@/api/login";
import { setTokenTime } from "@/utils/auh";
import router from "@/router";

export default {
  namespace: true,
  state() {
    return {
      token: localStorage.getItem("token") || "",
      siderType: false,
    };
  },
  mutations: {
    setToken(state, token) {
      (state.token = token), localStorage.setItem("token", token);
    },
    deleteToken(state) {
      localStorage.clear(), (state.token = "");
    },
    changeSideType(state) {
      state.siderType = !state.siderType;
    },
  },
  actions: {
    appLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            console.log(res.data);
            setTokenTime();
            commit("setToken", res.data);
            router.replace("/");
            resolve();
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    logout({ commit }) {
      commit("deleteToken");
      router.replace("/login");
    },
  },

  getters: {
    getToken(state) {
      return state.token;
    },
    getSideType(state) {
      return state.siderType;
    },
  },
};
